package com.qingke.besuper.command.impl;

import com.qingke.besuper.command.UserCommand;
import com.qingke.besuper.pojo.User;
import com.qingke.besuper.util.BeSuperConsole;

public class AskCommand extends UserCommand{

	public AskCommand(User user) {
		super(user);
	}

	@Override
	public void execute() {
		String context;
		String creditStr;
		int creditInt;
		int length;
		while(true){
			context=BeSuperConsole.promptNotEmpty("Please input question:");
			length=context.length();
			if(length>45){
				BeSuperConsole.println("You can only enter 45 characters.");
				BeSuperConsole.println();
				continue;
			}
			break;
		}
		while(true){
			creditStr=BeSuperConsole.promptNotEmpty("Please input credit:").trim();
			if(creditStr.trim().replaceAll("[0-9]","").equals("")){
				creditInt=Integer.parseInt(creditStr);
			}
			else{
				BeSuperConsole.println("Please input right credit.");
				BeSuperConsole.println();
				continue;
			}
			break;
		}
		if(creditInt<0){
			creditInt=0;
			BeSuperConsole.println("You set the question's credit = "+creditInt+" .");
			BeSuperConsole.println();
		}
		else if(creditInt>this.user.getScore()){
			creditInt=this.user.getScore();
			this.user.setScore(0);
			BeSuperConsole.println("The credit you set is more than your score,");
			BeSuperConsole.println("so the credit is setted to your all score , credit = "+creditInt+" .");
			BeSuperConsole.println();
		}
		else{
			this.user.setScore(this.user.getScore()-creditInt);
			BeSuperConsole.println("You set the question's credit = "+creditInt+" .");
			BeSuperConsole.println();
		}
		
		int isSuccess=dao.insertQuestion(context, creditInt,this.user.getId());
		if(isSuccess>0){
			dao.updateScore(this.user.getId(),this.user.getScore());
			BeSuperConsole.println("ask success");
		}
		else
			BeSuperConsole.println("ask failed");
		
	}

}
